package org.javaopenaccess.web.ui.login;

import java.util.Map;

import org.javaopenaccess.forms.UserForm;
import org.javaopenaccess.service.user.UserService;
import org.javaopenaccess.web.ui.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.zhtml.Messagebox;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

public class LoginController extends Window {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6575620885138147599L;
	private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	private UserService userService;
	private Validator loginValidator;
	
	public void onLogin(){
		logger.info("on login");
		//FIXME:These should be bound
		Textbox usernameBox = (Textbox)this.getFellow("username");
		Textbox passwordBox = (Textbox)this.getFellow("password");
		String userName = usernameBox.getValue().trim();
		String password = passwordBox.getValue().trim();
		UserForm form = new UserForm(userName, password);
		Map<Object, Object> errors = loginValidator.validate(form);
		
		if (errors == null){// validate user input
			UserForm user  = userService.getUser(form);	
			if (user != null){
				//this.detach();
				//Executions.createComponents("model.zul",null,null);
				Executions.sendRedirect("frontpage.html");
				return;
			}
		}
		try {
			Messagebox.show("Wrong username or password","Could not login", 
					Messagebox.OK,Messagebox.INFORMATION);
		} catch (InterruptedException ex) {
			logger.error("Could not show messagedialog", ex);
		}
	}
	
	public void onCreateNew(){
		this.detach();
		Executions.createComponents("register.zul",null,null);
	}
	
	public void onCreate(){
		logger.info("fetching spring beans");
		try {
			userService = (UserService)SpringUtil.getBean("userService");
			loginValidator = (Validator)SpringUtil.getBean("loginValidator");
		}catch (IllegalStateException ex){
			logger.error("error, could not load spring beans!", ex);
		}
		//Setting the default locale to en
		//Locale preferredLocale = new Locale("en_US");    
	    //session.setAttribute("px_preferred_locale", preferredLocale);
	}
}
